package com.core.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.amqp.support.converter.SimpleMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

@Configuration
public class RabbitMQConfig {

    @Bean
    public TopicExchange reservationExchange() {
        // 创建一个名为 "reservation.exchange" 的 Topic 类型的交换机
        return new TopicExchange("reservation.exchange", true, false);
    }

    @Bean
    public Queue emailQueue() {
        // 创建一个名为 "email.queue" 的队列
        return new Queue("email.queue", true);
    }

    @Bean
    public Binding emailBinding(Queue emailQueue, TopicExchange reservationExchange) {
        // 创建一个绑定关系 (Binding)
        return BindingBuilder.bind(emailQueue)         // 把 "email.queue" 队列
                .to(reservationExchange)   // 绑定到 "reservation.exchange" 交换机
                .with("reservation.success"); // 绑定键 (Binding Key)
    }

    /**
     * 定义一个消息转换器，使用 Jackson 将对象序列化为 JSON
     * 要是不用转换器直接发送的话会一直报错
     */
    @Bean
    public MessageConverter jsonMessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 自定义 RabbitTemplate，并为其设置我们定义的 MessageConverter
     * @param connectionFactory Spring Boot 自动配置好的连接工厂
     */
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        // 设置消息转换器为我们定义的 JSON 转换器
        template.setMessageConverter(jsonMessageConverter());
        return template;
    }

}